
function TreeNode(val) {
    this.val = val;
    this.left = null;
    this.right = null;
}


var levelOrder = function (root) {
    const queue = []
    queue.push(root)
    const res = []
    console.log(queue);


    while (queue.length) {
        const arr = []
        const len = queue.length

        for (let i = 0; i < len; i++) {
            const top = queue.shift()
            arr.push(top.val)

            if (top.left) {
                queue.push(top.left)
            }
            if (top.right) {
                queue.push(top.right)
            }
        }

        res.push(arr)

    }

    return res
}

const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);

console.log(levelOrder(root));



var flatten = function (root) {
    if (!root) return null;
    function pre(root) {
        if (!root) return null;
        let temp = root.right;
        root.right = root.left;
        let node = flatten(root.left);
        if (node) node.right = flatten(temp);
        root.left = null;
        return node.right ? node.right : node;
    }
    return root;
};
